/**
 * 封装 axios 请求模块
 */
import axios from 'axios'
import store from '@/store'
import config from '@/config' // 项目全局配置
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'
import { resetRouter } from '@/utils/router'

// 创建 axios实例
const request = axios.create({
  //  默认设置
  baseURL: config.baseURL, // 基础API路径
  timeout: 8000 // 响应超时 8000毫秒
})
// 请求拦截器
request.interceptors.request.use(
  config => {
    const superUserInfo = store.getters.SUPER_USER_INFO
    NProgress.start()
    if (superUserInfo) {
      config.headers.token = superUserInfo.token
    }
    if (config.auth) {
      config.headers.auth = config.auth
    }
    return config
  },
  error => {
    Message({ message: error.message, type: 'error', duration: 1000 })
    return Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use(
  response => {
    // 获取相应数据
    NProgress.done()
    const res = response.data
    if (res.status === 200) {
      // 正常情况
      return res.data
    } else if (res.status === 401) {
      const superUserInfo = store.getters.SUPER_USER_INFO
      if (superUserInfo) {
        store.commit('SET_SUPER_USER_INFO', null)
        store.commit('SET_ASYNC_ROUTE', null)
        resetRouter()
        window.location.hash = '/login'
        Message({ message: res.msg, type: 'error', duration: 2000 })
      }
      return false
    } else {
      // 服务器返回状态码错误
      Message({ message: res.msg, type: 'error', duration: 1000 })
      return false
    }
  },
  error => {
    // 响应失败
    Message({ message: error.message, type: 'error', duration: 1000 })
    return Promise.reject(error)
  }
)
// 导出请求模块
export default request
